  <template>
    <div class="comment-page">
      <!-- Toast 提示组件 -->
      <Toast ref="toastRef" />
      
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner">加载中...</div>
      </div>
      <div class="content-container">
      <!-- 左侧功能区域 -->
      <div class="left-panel">
        <!-- 楼盘搜索区域 -->
        <div class="search-section">
          <h3>🏢 楼盘搜索</h3>
          <div class="search-group">
            <v-select
              v-model="selecteUpdEstate"
              :options="estateOptions"
              :filterable="false"
              @search="onEstateSearch"
              placeholder="输入关键词搜索楼盘..."
              class="search-select"
            >
              <template #no-options>
                <div>输入关键词开始搜索...</div>
              </template>
            </v-select>
          </div>
        </div>

        <!-- 当前用户信息显示 -->
        <!-- <div class="current-user-section">
          <h3>👤 当前用户</h3>
          <div class="current-user-info">
            <span class="current-user-name">{{ currentUserName }}</span>
          </div>
        </div> -->

        <!-- 评论输入区域 -->
        <div class="input-section">
          <h3>💬 评论输入</h3>
          <textarea
            v-model="contentInput"
            placeholder="请输入评论内容..., 如果上传多条，每个评论之间请以\n来分隔。                            例如：评论内容1\n评论内容2\n评论内容3"
            class="content-textarea"
            rows="20"
          ></textarea>
        </div>

        <!-- 上传图片只能上传一个 -->
        <div class="image-upload-section">
          <h3>🖼️ 上传图片</h3>
          <div class="image-upload-container">
            <div v-if="!selectedImage" class="image-upload-placeholder" @click="triggerFileInput" :class="{ uploading: imageUploading }">
              <div v-if="imageUploading" class="upload-loading">
                <div class="loading-spinner-small"></div>
                <div class="upload-text">上传中...</div>
              </div>
              <div v-else>
                <div class="upload-icon">📷</div>
                <div class="upload-text">点击上传图片</div>
                <div class="image-upload-hint">支持 JPG、PNG、GIF 格式</div>
              </div>
            </div>
            <div v-else class="image-preview-container">
              <img :src="selectedImage" alt="预览图片" class="image-preview" />
              <div class="image-actions">
                <button @click="removeImage" class="remove-image-btn" title="删除图片">
                  🗑️
                </button>
                <button @click="triggerFileInput" class="change-image-btn" title="更换图片">
                  🔄
                </button>
              </div>
              <div v-if="uploadedImage" class="image-name">{{ uploadedImage.name }}</div>
            </div>
            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              @change="handleImageUpload"
              style="display: none"
            />
          </div>
        </div>

        <!-- 上传按钮区域 -->
        <div class="upload-section">
          <button @click="UploadCommentModal" class="upload-btn" :disabled="!canUploadErp || imageUploading">
            📤 上传到评论后台
          </button>
          <div v-if="!canUploadErp" class="upload-hint">
            <small>请选择楼盘、输入评论内容</small>
          </div>
        </div>
      </div>

      <!-- 上传弹窗 -->
      <div v-if="uploadModalVisible" class="modal-overlay" @click="hideUploadModal">
        <div class="modal-content" @click.stop>
          <div class="modal-header">
            <h3>📤 上传评论确认</h3>
            <button @click="hideUploadModal" class="modal-close">×</button>
          </div>
          <div class="modal-body">
            <div class="modal-item">
              <label>楼盘名称：</label>
              <span class="modal-value">{{ upEstateName || '未选择楼盘' }}</span>
            </div>
            <div class="modal-item">
              <label>用户名：</label>
              <span class="modal-value">{{ currentUserName || '未获取用户信息' }}</span>
            </div>
            <div class="modal-item">
              <label>选择时间：</label>
              <span class="modal-value">{{ formatDateTime(selectedDateTime) }}</span>
            </div>
            <div class="modal-item">
              <label>评论内容：</label>
              <div class="modal-comment-content">{{ finalContent || '未输入评论' }}</div>
            </div>
            <div class="modal-item" v-if="selectedImage">
              <label>上传图片：</label>
              <div class="modal-image-preview">
                <img :src="selectedImage" alt="上传图片" class="modal-image" />
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button @click="hideUploadModal" class="modal-btn cancel-btn">取消</button>
            <button @click="confirmUpload" class="modal-btn confirm-btn" :disabled="!canUpload">
              确认上传
            </button>
          </div>
        </div>
      </div>

      <!-- 右侧数据展示区域 -->
      <div class="right-panel">
        <!-- 筛选区域 -->
        <div class="filter-section">
          <h3>🔍 筛选条件</h3>
          <div class="filter-row">
            <!-- 楼盘搜索 -->
            <div class="filter-group">
              <v-select
                v-model="selectedEstate"
                :options="estateOptions"
                :filterable="false"
                @search="onEstateSearch"
                placeholder="搜索楼盘..."
                class="filter-select estate-select"
              >
                <template #no-options>
                  <div>输入关键词开始搜索...</div>
                </template>
              </v-select>
              <button @click="searchEstate" class="filter-btn">🔍</button>
            </div>
            
            <div class="filter-group">
              <input
                v-model="titleSearch"
                type="text"
                placeholder="搜索评价内容..."
                class="filter-input"
              />
              <button @click="searchByTitle" class="filter-btn">🔍</button>
            </div>
            
            <div class="filter-group">
              <input
                v-model="startDate"
                type="date"
                class="filter-input"
                @change="onDateChange"
              />
              <span class="filter-label">至</span>
              <input
                v-model="endDate"
                type="date"
                class="filter-input"
                @change="onDateChange"
              />
            </div>
            
            <div class="filter-group">
              <select v-model="sourceFilter" class="filter-select" @change="onSourceChange">
                <option value="">全部来源</option>
                <option value="小红书">小红书</option>
                <option value="微信">微信</option>
                <option value="网站">网站</option>
                <option value="抖音">抖音</option>
                <option value="用户">用户</option>
              </select>
            </div>

            <div class="filter-group">
              <select v-model="statusFilter" class="filter-select" @change="onStatusChange">
                <option value="">全部状态</option>
                <option value="has_value_1_and_is_use_0">有价值未审核</option>
                <option value="has_value_1_and_is_use_2">有价值已排除</option>
                <option value="has_value_1">有价值</option>
                <option value="has_value_0">无价值</option>
                <option value="is_use_0">未审核</option>
                <option value="is_use_1">已采用</option>
                <option value="is_use_2">未采用</option>
              </select>
            </div>
          
          </div>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
          <h3>📊 智能评论数据</h3>
        
          <!-- 弹窗组件 -->
          <div v-if="tooltipVisible" class="tooltip" :style="tooltipStyle">
            <div class="tooltip-content">{{ tooltipText }}</div>
          </div>
          <div class="table-container">
            <table class="data-table">
              <thead>
                <tr>
                  <th>评价内容</th>
                  <th>原文标题</th>
                  <th>链接</th>
                  <th>来源</th>
                  <th>创建时间</th>
                  <th>关联楼盘</th>
                  <th>机器审核</th>
                  <th>是否采用</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in paginatedData" :key="item.id || index">
                  <td class="content-cell">
                    <div 
                      class="content-text"
                      @mouseenter="showTooltip($event, item.content)"
                      @mouseleave="hideTooltip"
                    >
                      {{ truncateContent(item.content) }}
                    </div>
                  </td>
                  <td class="extract-cell">
                    <div 
                      class="extract-content"
                      @mouseenter="showTooltip($event, item.ai_content)"
                      @mouseleave="hideTooltip"
                    >
                      {{ truncateContent(item.ai_content) }}
                    </div>
                  </td>
                  <td class="link-cell">
                    <a :href="item.url" target="_blank" class="content-link">
                      🔗 查看
                    </a>
                  </td>
                  <td class="source-cell">
                    <span class="source-tag" :class="getSourceClass(item.from)">
                      {{ getSourceName(item) }}
                    </span>
                  </td>
                  <td class="time-cell">
                    {{ formatTime(item.create_time) }}
                  </td>
                  <td class="property-cell">{{ formatEstateName(item.estate_name) }}</td>
                  <td class="review-cell">
                    <span class="review-tag" :class="getReviewClass(item.has_value)">
                      {{ getReviewName(item.has_value) }}
                    </span>
                  </td>
                  <td class="status-cell">
                    <div class="status-buttons">
                      <button 
                        @click="showAdoptModal(item)"
                        class="status-btn correct-btn"
                        :class="{ active: item.is_use === 1 }"
                        :disabled="loading"
                        title="标记为已采用"
                      >
                        <span class="btn-text">已采用</span>
                      </button>
                      <button 
                        @click="updateArticleAdopt(item.id, 2)"
                        class="status-btn error-btn"
                        :class="{ active: item.is_use === 2 }"
                        :disabled="loading"
                        title="标记为未采用"
                      >
                        <span class="btn-text">未采用</span>
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页控件 -->
          <div class="pagination">
            <button 
              @click="prevPage" 
              :disabled="currentPage === 1"
              class="page-btn"
            >
              ← 上一页
            </button>
            <span class="page-info">
              第 {{ currentPage }} 页，共 {{ totalPages }} 页
            </span>
            <button 
              @click="nextPage" 
              :disabled="currentPage >= totalPages"
              class="page-btn"
            >
              下一页 →
            </button>
          </div>
        </div>
      </div>

      <!-- 采用弹窗 -->
      <div v-if="adoptModalVisible" class="modal-overlay" @click="hideAdoptModal">
        <div class="modal-content adopt-modal" @click.stop>
          <div class="modal-header">
            <h3>📝 采用评论</h3>
            <button @click="hideAdoptModal" class="modal-close">×</button>
          </div>
          <div class="modal-body">
            <!-- 楼盘信息展示 -->
            <div class="adopt-section">
              <h4>🏢 选择楼盘</h4>
              <div class="adopt-estate-search">
                <v-select
                  v-model="adoptSelectedEstate"
                  :options="adoptEstateOptions"
                  :filterable="false"
                  @search="onAdoptEstateSearch"
                  placeholder="输入关键词搜索楼盘..."
                  class="adopt-search-select"
                >
                  <template #no-options>
                    <div>输入关键词开始搜索...</div>
                  </template>
                </v-select>
              </div>
            </div>

            <!-- 评论内容 -->
            <div class="adopt-section">
              <h4>💬 评论内容</h4>
              <textarea
                v-model="adoptContentInput"
                placeholder="请输入评论内容..."
                class="adopt-content-textarea"
                rows="8"
              ></textarea>
            </div>

            <!-- AI改写 -->
            <div class="adopt-section">
              <h4>🤖 AI改写</h4>
              <div class="adopt-rewrite-actions">
                <button @click="handleAdoptRewriteContent" class="adopt-rewrite-btn" :disabled="!adoptContentInput.trim()">
                  ✨ 改写评论
                </button>
              </div>
              <textarea
                v-model="adoptRewriteContent"
                placeholder="AI改写后的内容将显示在这里..."
                class="adopt-rewrite-textarea"
                rows="6"
              ></textarea>
            </div>

            <!-- 时间选择 -->
            <div class="adopt-section">
              <h4>⏰ 时间选择</h4>
              <div class="adopt-time-input-group">
                <input
                  v-model="adoptSelectedDateTime"
                  type="datetime-local"
                  class="adopt-time-input"
                  step="1"
                />
                <button @click="setAdoptCurrentTime" class="adopt-time-btn">现在</button>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button @click="hideAdoptModal" class="modal-btn cancel-btn">取消</button>
            <button @click="confirmAdoptUpload" class="modal-btn confirm-btn" :disabled="!canAdoptUpload">
              确认采用
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import vSelect from 'vue-select';
import OSS from 'ali-oss';
import Toast from './Toast.vue';

// 左侧面板数据
const propertySearch = ref('');
const contentInput = ref('');
const upEstateId = ref('');
const upEstateName = ref('');
const rewriteContent = ref('');

// 当前用户信息
const currentUserName = ref('');
const currentUserId = ref('');

// 楼盘选择数据
const selectedEstate = ref(null);
const selecteUpdEstate = ref(null);
const estateOptions = ref([]);

// 右侧筛选数据
const titleSearch = ref('');
const startDate = ref('');
const endDate = ref('');
const sourceFilter = ref('');
const statusFilter = ref('');

// 上传弹窗状态
const uploadModalVisible = ref(false);
const selectedDateTime = ref('');

// 采用弹窗状态
const adoptModalVisible = ref(false);
const adoptContentInput = ref('');
const adoptRewriteContent = ref('');
const adoptSelectedDateTime = ref('');
const currentAdoptItem = ref(null);
const adoptSelectedEstate = ref(null);
const adoptEstateOptions = ref([]);

// 图片上传相关
const selectedImage = ref(null);
const fileInput = ref(null);
const imageUploading = ref(false);

// Toast 组件引用
const toastRef = ref(null);

// 上传的图片信息
const uploadedImage = ref(null);

// OSS配置
let ossClient = null;
let ossParams = null;

// 获取OSS上传参数
const getOSSParams = async () => {
  try {
    const response = await axios.get('/api/erp/screenshot/data/oss');
    if (response.data && response.data.data) {
      ossParams = response.data.data;
      console.log('获取OSS参数成功:', ossParams);
      return ossParams;
    } else {
      throw new Error('OSS参数响应格式错误');
    }
  } catch (error) {
    console.error('获取OSS参数失败:', error);
    throw error;
  }
};

// 初始化OSS客户端
const initOSSClient = async () => {
  try {
    // 先获取OSS参数
    if (!ossParams) {
      await getOSSParams();
    }
    
    ossClient = new OSS({
      region: 'oss-cn-hangzhou',
      accessKeyId: ossParams.OSSAccessKeyId,
      accessKeySecret: '8jPhIKCqdJ0DWe0RYiEyFsjIKVlI70',
      internal: false,
      bucket: 'xiaoji-hangzhou',
      timeout: 60000, // 60秒超时
      secure: true, // 使用HTTPS
      cname: false, // 不使用自定义域名
      retryMax: 3, // 最大重试次数
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization'
      }
    });
    console.log('OSS客户端初始化成功');
  } catch (error) {
    console.error('OSS客户端初始化失败:', error);
  }
};



// API配置
const API_ENDPOINT = '/media/article/search/estate/comment';

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);

// 加载状态
const loading = ref(false);

// 弹窗状态
const tooltipVisible = ref(false);
const tooltipText = ref('');
const tooltipStyle = ref({
  left: '0px',
  top: '0px'
});

// 获取最近一周的日期范围
const getLastWeekRange = () => {
  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - 7);
  
  return {
    start: start.toISOString().split('T')[0], // 格式：2025-01-07
    end: end.toISOString().split('T')[0]
  };
};

// 模拟数据
const tableData = ref([]);

// 计算属性
const canUpload = computed(() => {
  return (rewriteContent.value.trim() || contentInput.value.trim()) && adoptSelectedDateTime.value && upEstateId.value && upEstateName.value;
});

const canUploadErp = computed(() => {
  return selecteUpdEstate.value && (contentInput.value || uploadedImage.value?.originalUrl) && currentUserName.value
});


// 最终使用的评论内容（优先使用改写后的内容）
const finalContent = computed(() => {
  return rewriteContent.value.trim() || contentInput.value;
});

// 采用弹窗的最终内容
const adoptFinalContent = computed(() => {
  return adoptRewriteContent.value.trim() || adoptContentInput.value;
});

// 采用弹窗的上传条件
const canAdoptUpload = computed(() => {
  return adoptContentInput.value.trim() && adoptSelectedDateTime.value && adoptSelectedEstate.value;
});

// 总页数
const totalPages = ref(0);

// 前端分页计算 - 从累积数据中截取当前页数据
const paginatedData = computed(() => {
  return tableData.value;
});

// 获取当前用户信息
const getCurrentUserInfo = () => {
  try {
    const userInfoStr = sessionStorage.getItem('user_info');
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr);
      currentUserName.value = userInfo.name || userInfo.username || '';
      currentUserId.value = userInfo.id || '';
      console.log('获取当前用户信息:', currentUserName.value);
    } else {
      currentUserName.value = '';
      console.log('未找到用户信息');
    }
  } catch (error) {
    console.error('解析用户信息失败:', error);
    currentUserName.value = '';

  }
};

// 楼盘搜索方法
const onEstateSearch = (search, loading) => {
  if (search.length) {
    loading(true);
    axios.post('/formal/erp/ai/get/searchEstateName', {
      search: search
    })
    .then(response => {
      if (response.data && Array.isArray(response.data.data)) {
        estateOptions.value = response.data.data.map(item => ({
          label: item.real_estate_name,
          id: item.id,
          type: item.type,
          value: item.real_estate_name + '(' + item.type + ')'
        }));
      } else {
        estateOptions.value = [];
      }
    })
    .catch(error => {
      console.error("楼盘搜索API调用失败:", error);
      estateOptions.value = [];
    })
    .finally(() => {
      loading(false);
    });
  }
};

// 采用弹窗楼盘搜索方法
const onAdoptEstateSearch = (search, loading) => {
  if (search.length) {
    loading(true);
    axios.post('/formal/erp/ai/get/searchEstateName', {
      search: search
    })
    .then(response => {
      if (response.data && Array.isArray(response.data.data)) {
        adoptEstateOptions.value = response.data.data.map(item => ({
          label: item.real_estate_name + '(' + item.type + ')',
          id: item.id,
          type: item.type,
          value: item.real_estate_name
        }));
      } else {
        adoptEstateOptions.value = [];
      }
    })
    .catch(error => {
      console.error("采用弹窗楼盘搜索API调用失败:", error);
      adoptEstateOptions.value = [];
    })
    .finally(() => {
      loading(false);
    });
  }
};

// API请求方法
const fetchComments = async (params = {}) => {
  try {
    loading.value = true;
    
    // 构建请求参数
    const requestParams = {
      page: params.page || currentPage.value,
      page_size: pageSize.value,
      estate_id: params.estate_id || selectedEstate.value?.id,
      content: params.content || titleSearch.value,
      from_source: params.from_source || sourceFilter.value,
      start_time: params.start_time || startDate.value,
      end_time: params.end_time || endDate.value
    };


    // 处理状态筛选
    if (statusFilter.value) {
      if (statusFilter.value === 'has_value_1_and_is_use_0') {
        // 有价值未审核：has_value=1 且 is_use=0
        requestParams.has_value = 1;
        requestParams.is_use = 0;
      } else if (statusFilter.value === 'has_value_1_and_is_use_2') {
        // 有价值已排除：has_value=1 且 is_use=2
        requestParams.has_value = 1;
        requestParams.is_use = 0;
        requestParams.ip_type = 'ip';
      } else {
        const [field1, field2, value] = statusFilter.value.split('_');
        console.log('状态筛选:', field1, field2, value);
        let field = field1 + '_' + field2;
        if (field === 'has_value') {
          requestParams.has_value = parseInt(value);
        } else if (field === 'is_use') {
          requestParams.is_use = parseInt(value);
        }
      }
    }

    if (requestParams.from_source === '全部来源') {
      delete requestParams.from_source;
    }
    
    // 移除空值参数
    Object.keys(requestParams).forEach(key => {
      if (!requestParams[key] && requestParams[key] !== 0) {
        delete requestParams[key];
      }
    });
    
    const response = await axios.post(`${API_ENDPOINT}`, requestParams, {
      headers: {
        'Content-Type': 'application/json',  // 明确指定 JSON 格式
      },
    });
    
    if (response.data && response.data.success) {
      // 累积数据 - 第一页替换，其他页追加
      tableData.value = response.data.list || [];
      totalPages.value = response.data.total || 0;
    } else {
      console.error('API请求失败:', response.data);
    }
  } catch (error) {
    console.error('请求出错:', error);
    // 如果API请求失败，使用模拟数据
    console.log('使用模拟数据');
  } finally {
    loading.value = false;
  }
};

// 初始化数据
const initData = () => {
  const { start, end } = getLastWeekRange();
  startDate.value = start;
  endDate.value = end;
  // 设置默认显示未审核的数据
  statusFilter.value = 'is_use_0';
  console.log('初始化时间范围:', start, '到', end);
  console.log('默认显示未审核数据');
  fetchComments();
};


// 设置当前时间为选中时间
const setCurrentTime = () => {
  const now = new Date();
  // 获取本地时间的偏移量（分钟）
  const timezoneOffset = now.getTimezoneOffset();
  // 创建本地时间
  const localTime = new Date(now.getTime() - (timezoneOffset * 60 * 1000));
  selectedDateTime.value = localTime.toISOString().slice(0, 19);
};

// AI改写评论内容
const handleRewriteContent = async () => {
  if (!contentInput.value.trim()) {
    if (toastRef.value) {
      toastRef.value.show('请先输入评论内容', 'warning', 2000);
    }
    return;
  }

  try {

    const requestParams = {
      content: contentInput.value
    };

    const response = await axios.post(`/media/article/ai/rewrite/estate/comment`, requestParams, {
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (response.data && response.data.success) {
      rewriteContent.value = response.data.data || response.data.rewritten_content || '';
      console.log('AI改写成功');
    } else {
      console.error('AI改写失败:', response.data);
      if (toastRef.value) {
        toastRef.value.show('AI改写失败，请重试', 'error', 3000);
      }
    }
  } catch (error) {
    console.error('AI改写出错:', error);
    if (toastRef.value) {
      toastRef.value.show('AI改写出错，请重试', 'error', 3000);
    }
  } 
};

// 用户添加评论
const UploadCommentModal = async () => {
  // 处理转义的换行符，先替换\\n为实际的换行符，再分割
  let list = contentInput.value.replace(/\\n/g, '\n').split('\n').filter(item => item.trim() !== '');

  if (!currentUserName.value) {
    if (toastRef.value) {
      toastRef.value.show('用户信息获取失败，请重新登录', 'error', 3000);
    }
    return;
  }

  if (list.length > 0 || uploadedImage.value?.originalUrl) {
    // 显示临时弹窗
    const tempModal = document.createElement('div');
    tempModal.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 20px 30px;
      border-radius: 8px;
      font-size: 16px;
      z-index: 9999;
      display: flex;
      align-items: center;
      gap: 10px;
    `;
    tempModal.innerHTML = `
      <div style="width: 20px; height: 20px; border: 2px solid #fff; border-top: 2px solid transparent; border-radius: 50%; animation: spin 1s linear infinite;"></div>
      <span>正在上传评论，请稍候... 弹窗持续10s后自动关闭</span>
    `;
    
    // 添加旋转动画样式
    const style = document.createElement('style');
    style.textContent = `
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    `;
    document.head.appendChild(style);
    document.body.appendChild(tempModal);

    // 1.5秒后自动关闭弹窗
    setTimeout(() => {
        document.body.removeChild(tempModal);
        document.head.removeChild(style);
      }, 10000);

    try {
      let requestParams = {
        comment_list:[],
        image_url:uploadedImage.value?.originalUrl || null,
        user_name: currentUserName.value,
        estate_name:selecteUpdEstate.value.value,
        estate_id:selecteUpdEstate.value.id,
      }
      for (let i = 0; i < list.length; i++) {
        let content = list[i]
        requestParams.comment_list.push({
            estate_name:selecteUpdEstate.value.value,
            estate_id:selecteUpdEstate.value.id,
            comment:content,
            create_time:selectedDateTime.value.replace('T', ' '),
            from_source:"用户",
            user_name: currentUserName.value,
        })
      }

      const response = await axios.post(`/media/article/save/estate/comment`, requestParams, {
          headers: {
            'Content-Type': 'application/json',
          },
        });

        if (response.data && response.data.success) {
          // 清空输入
          contentInput.value = '';
        }
      
      // 使用Toast显示成功消息
      if (toastRef.value) {
        toastRef.value.show(`上传成功 ${list.length} 条评论`, 'success', 1500);
      }
      
      // 关闭临时弹窗
      document.body.removeChild(tempModal);
      document.head.removeChild(style);
      
    } catch (error) {
      // 使用Toast显示错误消息
      if (toastRef.value) {
        toastRef.value.show(`上传失败: ${error.message}`, 'error', 3000);
      }
      
      console.error('Upload error:', error);
      
      // 关闭临时弹窗
      document.body.removeChild(tempModal);
      document.head.removeChild(style);
    }
  } else {
      if (toastRef.value) {
        toastRef.value.show('请先选择楼盘和输入评论内容', 'warning', 2000);
      }
  }
};

// 隐藏上传弹窗
const hideUploadModal = () => {
  uploadModalVisible.value = false;
};

// 防抖函数
const debounce = (func, delay) => {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
};

// 上传到小鸡后台
const confirmUpload = debounce(async () => {
  if (!canUpload.value) {
    alert('请检查楼盘名称、评论内容和时间是否已填写。');
    return;
  }
  
  try {
    loading.value = true;
    const requestParams = {
      real_estate_id: upEstateId.value,
      words: adoptFinalContent.value,
      create_time: adoptSelectedDateTime.value.replace('T', ' '),
      type: '点评',
      up_user: currentUserId.value
    };

    const response = await axios.post(`/formal/erp/ai/addEstateComment`, requestParams, {
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (response.data && response.data.success) {
      console.log('评论上传成功');
      // 清空输入
      contentInput.value = '';
      rewriteContent.value = '';
      upEstateId.value = '';
      upEstateName.value = '';
      hideUploadModal();
    } else {
      console.error('评论上传失败:', response.data);
    }
  } catch (error) {
    console.error('上传评论出错:', error);
  } finally {
    loading.value = false;
  }
}, 500); // 500ms 防抖延迟

const searchEstate = () => {
  currentPage.value = 1;
  fetchComments({
    estate_id: selectedEstate.value?.id || '',
    page: 1
  });
};

const searchByTitle = () => {
  currentPage.value = 1;
  fetchComments({
    content: titleSearch.value,
    page: 1
  });
};

// 日期变化处理
const onDateChange = () => {
  // 只有当开始时间和结束时间都设置了才触发搜索
  if (startDate.value && endDate.value) {
    currentPage.value = 1;
    fetchComments({
      start_time: startDate.value,
      end_time: endDate.value,
      page: 1
    });
  }
};

// 来源变化处理
const onSourceChange = () => {
  currentPage.value = 1;
  fetchComments({
    from_source: sourceFilter.value,
    page: 1
  });
};

// 状态筛选变化处理
const onStatusChange = () => {
  currentPage.value = 1;
  fetchComments({
    page: 1
  });
};


const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchComments({
      page: currentPage.value
    });
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchComments({
    page: currentPage.value
  });
  }
};

const getSourceClass = (source) => {
  const classes = {
    '小红书': 'source-xiaohongshu',
    '微信': 'source-wechat',
    '网站': 'source-website',
    '抖音': 'source-douyin',
    '用户': 'source-user'
  };
  return classes[source] || 'source-default';
};

const getSourceName = (source) => {
  if (source.user_name) {
    return source.user_name;
  }
  return source.from || '未知';
};


// 机器审核状态
const getReviewClass = (review) => {
  const classes = {
    '1': 'review-pass',
    '0': 'review-reject',
  };
  return classes[review] || 'review-default';
};

const getReviewName = (review) => {
  const names = {
    '1': '有价值',
    '0': '无价值',
  };
  return names[review] || review || '未知';
};

// 判断是否应该从当前视图中删除数据
const shouldRemoveFromCurrentView = (newStatus) => {
  // 如果当前筛选条件是"全部状态"，则不删除任何数据
  if (statusFilter.value === '') {
    return false;
  }
  
  // 如果当前筛选条件是"未审核"，但数据状态变成了"已采用"或"未采用"，则应该删除
  if (statusFilter.value === 'is_use_0' && newStatus !== 0) {
    return true;
  }
  // 如果当前筛选条件是"已采用"，但数据状态变成了"未采用"，则应该删除
  if (statusFilter.value === 'is_use_1' && newStatus !== 1) {
    return true;
  }
  // 如果当前筛选条件是"未采用"，但数据状态变成了"已采用"，则应该删除
  if (statusFilter.value === 'is_use_2' && newStatus !== 2) {
    return true;
  }
  // 如果当前筛选条件是"有价值"，但数据状态变成了"无价值"，则应该删除
  if (statusFilter.value === 'has_value_1' && newStatus !== 1) {
    return true;
  }
  // 如果当前筛选条件是"无价值"，但数据状态变成了"有价值"，则应该删除
  if (statusFilter.value === 'has_value_0' && newStatus !== 0) {
    return true;
  }
  // 如果当前筛选条件是"有价值未审核"，但数据状态变成了"已采用"或"未采用"，则应该删除
  if (statusFilter.value === 'has_value_1_and_is_use_0' && newStatus !== 0) {
    return true;
  }
  // 其他情况不删除
  return false;
};

// 更新文章采用状态
const updateArticleAdopt = async (articleId, newAdoptStatus) => {
  try {
    loading.value = true;
    const response = await axios.post(`/media/article/update/estate/comment/is/use`, {
      article_id: articleId,
      status: newAdoptStatus
    }, {
      timeout: 10000
    });

    // 未采用上传到小程序
    if (newAdoptStatus === 2) {
      const find = tableData.value.find(item => item.id === articleId);
      if (find) {
        const res = await axios.post(`/formal/erp/ai/add/estate/comment/not/used`, {
          up_user: currentUserId.value,
          estate_id: find.estate_id,
          words: find.content,
        }, {
          timeout: 10000
        });
      }
    }
    
    if (response.data && response.data.success) {
      // 更新本地数据
      const article = tableData.value.find(item => item.id === articleId);
      if (newAdoptStatus === 1) {
        contentInput.value = article.content
        upEstateId.value = article.estate_id
        upEstateName.value = article.estate_name
      }
      if (article) {
        article.is_use = newAdoptStatus;
      }
      
      // 根据当前筛选条件决定是否从列表中删除
      const shouldRemove = shouldRemoveFromCurrentView(newAdoptStatus);
      if (shouldRemove) {
        // 从当前页面删除该条数据
        const index = tableData.value.findIndex(item => item.id === articleId);
        if (index > -1) {
          tableData.value.splice(index, 1);
          console.log(`已从当前页面删除状态为 ${newAdoptStatus} 的数据`);
          
          // 显示成功消息
          const statusText = newAdoptStatus === 1 ? '已采用' : newAdoptStatus === 2 ? '未采用' : '未知状态';
          const filterText = statusFilter.value === 'is_use_0' ? '未审核' : 
                           statusFilter.value === 'is_use_1' ? '已采用' : 
                           statusFilter.value === 'is_use_2' ? '未采用' : 
                           statusFilter.value === 'has_value_1_and_is_use_0' ? '有价值未审核' : '当前筛选';
          
          // 使用Toast显示成功消息
          if (toastRef.value) {
            toastRef.value.show(`操作成功！该评论已标记为${statusText}`, 'success', 1500);
          }
          
          // 如果删除后当前页面没有数据了，且不是第一页，则跳转到上一页
          if (tableData.value.length === 0 && currentPage.value > 1) {
            currentPage.value--;
            fetchComments();
          }
        }
      }
      
      console.log('采用状态更新成功');
    } else {
      console.error('采用状态更新失败:', response.data);
    }
  } catch (error) {
    console.error('更新采用状态出错:', error);
  } finally {
    loading.value = false;
  }
};

// 显示采用弹窗
const showAdoptModal = (item) => {
  currentAdoptItem.value = item;
  adoptContentInput.value = item.content || '';
  adoptRewriteContent.value = '';
  
  // 设置默认选中的楼盘
  if (item.estate_name && item.estate_id) {
    adoptSelectedEstate.value = {
      label: item.estate_name,
      id: item.estate_id,
      type: item.estate_type || ''
    };
  } else {
    adoptSelectedEstate.value = null;
  }
  
  setAdoptCommentTime(item.create_time);
  adoptModalVisible.value = true;
};

// 隐藏采用弹窗
const hideAdoptModal = () => {
  adoptModalVisible.value = false;
  currentAdoptItem.value = null;
  adoptSelectedEstate.value = null;
  adoptEstateOptions.value = [];
};

// 设置采用弹窗评论创建时间
const setAdoptCommentTime = (createTime) => {
  if (createTime) {
    try {
      // 解析评论的创建时间
      const date = new Date(createTime);
      if (!isNaN(date.getTime())) {
        // 直接使用解析后的时间，不需要时区转换
        // 因为datetime-local输入框会自动处理时区
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        adoptSelectedDateTime.value = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
        console.log('设置评论创建时间:', adoptSelectedDateTime.value);
        return;
      }
    } catch (error) {
      console.error('解析评论创建时间失败:', error);
    }
  }
  
  // 如果解析失败或没有创建时间，使用当前时间作为后备
  console.log('使用当前时间作为后备');
  setAdoptCurrentTime();
};

// 设置采用弹窗当前时间（后备方案）
const setAdoptCurrentTime = () => {
  const now = new Date();
  const timezoneOffset = now.getTimezoneOffset();
  const localTime = new Date(now.getTime() - (timezoneOffset * 60 * 1000));
  adoptSelectedDateTime.value = localTime.toISOString().slice(0, 19);
};



// 采用弹窗AI改写
const handleAdoptRewriteContent = async () => {
  if (!adoptContentInput.value.trim()) {
    if (toastRef.value) {
      toastRef.value.show('请先输入评论内容', 'warning', 2000);
    }
    return;
  }

  try {
    const requestParams = {
      content: adoptContentInput.value
    };

    const response = await axios.post(`/media/article/ai/rewrite/estate/comment`, requestParams, {
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (response.data && response.data.success) {
      console.log('采用弹窗AI改写成功:', response.data);
      adoptRewriteContent.value = response.data.data || response.data.rewritten_content || '';
      console.log('采用弹窗AI改写成功');
    } else {
      console.error('采用弹窗AI改写失败:', response.data);
      if (toastRef.value) {
        toastRef.value.show('AI改写失败，请重试', 'error', 3000);
      }
    }
  } catch (error) {
    console.error('采用弹窗AI改写出错:', error);
    if (toastRef.value) {
      toastRef.value.show('AI改写出错，请重试', 'error', 3000);
    }
  }
};

// 上传到小程序
const confirmAdoptUpload = async () => {
  if (!canAdoptUpload.value) {
    if (toastRef.value) {
      toastRef.value.show('请检查评论内容和时间是否已填写。', 'warning', 3000);
    }
    return;
  }

  // 检查是否选择了楼盘
  if (!adoptSelectedEstate.value) {
    if (toastRef.value) {
      toastRef.value.show('请选择楼盘', 'warning', 3000);
    }
    return;
  }

  try {
    loading.value = true;
    
    // 先更新采用状态（这会触发数据删除逻辑）
    await updateArticleAdopt(currentAdoptItem.value.id, 1);

    // 然后执行上传操作，使用新选择的楼盘
    const requestParams = {
      real_estate_id: adoptSelectedEstate.value.id,
      words: adoptRewriteContent.value || adoptContentInput.value,
      create_time: adoptSelectedDateTime.value.replace('T', ' '),
      type: '点评',
      up_user: currentUserId.value
    };

    const response = await axios.post(`/formal/erp/ai/addEstateComment`, requestParams, {
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (response.data && response.data.success) {
      console.log('采用评论上传成功');
      if (toastRef.value) {
        toastRef.value.show('采用评论上传成功', 'success', 3000);
      }
    } else {
      console.error('采用评论上传失败:', response.data);
      if (toastRef.value) {
        toastRef.value.show('采用评论上传失败', 'error', 3000);
      }
    }
  } catch (error) {
    console.error('采用评论上传出错:', error);
    if (toastRef.value) {
      toastRef.value.show('采用评论上传出错', 'error', 3000);
    }
  } finally {
    loading.value = false;
    // 清空弹窗数据
    hideAdoptModal();
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  try {
    const date = new Date(timeStr);
    if (isNaN(date.getTime())) {
      return timeStr.split(' ')[0]; // 如果解析失败，只显示日期部分
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    return timeStr.split(' ')[0]; // 出错时只显示日期部分
  }
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未选择时间';
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 格式化楼盘名称
const formatEstateName = (estate_name) => {
  if (!estate_name) return '未关联楼盘';
  return estate_name;
};


// 截断内容显示
const truncateContent = (content) => {
  if (!content) return '';
  const lines = content.split('\n');
  if (lines.length <= 5) return content;
  return lines.slice(0, 5).join('\n') + '\n...';
};

// 显示弹窗
const showTooltip = (event, content) => {
  if (!content) return;
  
  const rect = event.target.getBoundingClientRect();
  // const tableRect = event.target.closest('.table-container').getBoundingClientRect();
  
  tooltipText.value = content;
  tooltipStyle.value = {
    left: `${rect.left + rect.width / 2}px`,
    top: `${rect.top - 10}px`
  };
  tooltipVisible.value = true;
};

// 隐藏弹窗
const hideTooltip = () => {
  tooltipVisible.value = false;
};

// 图片上传相关方法
const triggerFileInput = () => {
  fileInput.value?.click();
};

const handleImageUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    if (toastRef.value) {
      toastRef.value.show('请选择图片文件', 'warning', 2000);
    }
    return;
  }

  // 检查文件大小 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    if (toastRef.value) {
      toastRef.value.show('图片大小不能超过 5MB', 'warning', 2000);
    }
    return;
  }

  imageUploading.value = true;
  
  try {
    // 初始化OSS客户端
    if (!ossClient) {
      await initOSSClient();
    }

    // 生成唯一的文件名
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substring(2, 8);
    const fileExtension = file.name.split('.').pop();
    const fileName = `img/${timestamp}_${randomStr}.${fileExtension}`;

    console.log('开始上传文件:', file.name, '大小:', file.size);
    console.log('生成的文件名:', fileName);

    // 创建本地预览URL（base64）
    const reader = new FileReader();
    const previewPromise = new Promise((resolve, reject) => {
      reader.onload = (e) => resolve(e.target.result);
      reader.onerror = (e) => reject(e);
      reader.readAsDataURL(file);
    });
    const previewUrl = await previewPromise;

    try {
      // 使用从接口获取的参数生成预签名URL
      if (!ossParams) {
        await getOSSParams();
      }

      // 构建表单数据
      const formData = new FormData();
      formData.append('key', fileName);
      formData.append('policy', ossParams.policy);
      formData.append('OSSAccessKeyId', ossParams.OSSAccessKeyId);
      formData.append('signature', ossParams.signature);
      formData.append('success_action_status', '200');
      formData.append('file', file);

      // 直接上传到OSS
      const ossUploadResponse = await fetch('https://xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com', {
        method: 'POST',
        body: formData
      });

      if (ossUploadResponse.ok) {
        const finalUrl = `https://xiaoji-hangzhou.oss-cn-hangzhou.aliyuncs.com/${fileName}`;
        console.log('OSS表单上传成功:', finalUrl);
        
        // 保存上传的图片信息
        uploadedImage.value = {
          name: file.name,
          url: previewUrl, // 使用base64预览
          ossKey: fileName,
          originalUrl: finalUrl,
          uploaded: true
        };
        
        // 设置预览图片
        selectedImage.value = previewUrl;
        
        return finalUrl;
      } else {
        throw new Error(`OSS表单上传失败: ${ossUploadResponse.status} ${ossUploadResponse.statusText}`);
      }
    } catch (ossError) {
      console.error('OSS表单上传失败:', ossError);

      // 尝试直接OSS上传
      try {
        const result = await ossClient.put(fileName, file, {
          timeout: 60000,
          headers: {
            'Content-Type': file.type
          }
        });

        console.log('直接OSS上传成功:', result.url);

        // 保存上传的图片信息
        uploadedImage.value = {
          name: file.name,
          url: previewUrl,
          ossKey: fileName,
          originalUrl: result.url,
          uploaded: true
        };
        
        // 设置预览图片
        selectedImage.value = previewUrl;

        return result.url;
      } catch (directError) {
        console.error('直接OSS上传也失败:', directError);

        // 最后使用base64
        uploadedImage.value = {
          name: file.name,
          url: previewUrl,
          ossKey: fileName,
          originalUrl: previewUrl,
          uploaded: false
        };
        
        // 设置预览图片
        selectedImage.value = previewUrl;

        console.log('所有OSS上传方式失败，使用base64存储');
        return previewUrl;
      }
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    let errorMessage = '图片上传失败';

    if (error.code === 'AccessDenied') {
      errorMessage = '访问被拒绝，请检查OSS配置';
    } else if (error.code === 'NoSuchBucket') {
      errorMessage = '存储桶不存在';
    } else if (error.code === 'InvalidAccessKeyId') {
      errorMessage = 'AccessKey无效';
    } else if (error.message) {
      errorMessage += ': ' + error.message;
    }

    if (toastRef.value) {
      toastRef.value.show(errorMessage, 'error', 3000);
    }
  } finally {
    imageUploading.value = false;
  }
};

const removeImage = () => {
  selectedImage.value = null;
  uploadedImage.value = null;
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};



// 页面加载时初始化数据
onMounted(() => {
  console.log('页面加载，开始初始化数据...');
  initOSSClient(); // 初始化OSS客户端
  getCurrentUserInfo(); // 获取当前用户信息
  initData();
  // 设置默认时间为当前时间
  setCurrentTime();
});
</script>

<style scoped>
/* 确保页面占满整个视口 */
:deep(html), :deep(body) {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

:deep(#app) {
  height: 100vh;
  overflow: hidden;
}
.comment-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--panel-bg-color);
  border-radius: 12px;
  overflow: hidden;
  position: relative;
}

.content-container {
  flex: 1;
  display: flex;
  height: calc(100vh - 0px);
  overflow: hidden;
}

/* 左侧面板样式 */
.left-panel {
  width: 25%;
  padding: 24px;
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  gap: 24px;
  background: #fafbfc;
  overflow-y: auto;
  height: 100%;
}

.search-section {
  margin-bottom: 16px;
}

.current-user-section {
  margin-bottom: 16px;
}

.current-user-info {
  padding: 12px;
  background: #e3f2fd;
  border: 2px solid #2196f3;
  border-radius: 8px;
}

.current-user-name {
  font-size: 14px;
  color: #1976d2;
  font-weight: 500;
}



.search-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-select {
  flex: 1;
}

.search-btn {
  padding: 12px 16px;
  background: var(--primary-color);
  color: var(--text-color);
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.search-btn:hover:not(:disabled) {
  background: var(--primary-hover);
  transform: translateY(-1px);
}

.search-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.left-panel h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: var(--text-color);
  font-weight: 600;
}

/* 左侧面板 vue-select 样式 */
:deep(.search-select .vs__dropdown-toggle) {
  padding: 12px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  background: white;
  transition: border-color 0.3s ease;
}

:deep(.search-select .vs__dropdown-toggle:focus) {
  border-color: var(--primary-color);
  outline: none;
}

:deep(.search-select .vs__search) {
  padding: 0;
  margin: 0;
  border: none;
  background: transparent;
  font-size: 14px;
  color: var(--text-color);
}

:deep(.search-select .vs__search::placeholder) {
  color: #94a3b8;
}

:deep(.search-select .vs__dropdown-menu) {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: white;
}

:deep(.search-select .vs__dropdown-option) {
  padding: 12px;
  font-size: 14px;
  color: var(--text-color);
  transition: background-color 0.2s ease;
}

:deep(.search-select .vs__dropdown-option--highlight) {
  background: var(--primary-color);
  color: white;
}

:deep(.search-select .vs__dropdown-option--selected) {
  background: rgba(59, 130, 246, 0.1);
  color: var(--primary-color);
}

:deep(.search-select .vs__clear) {
  display: none;
}

:deep(.search-select .vs__open-indicator) {
  fill: var(--text-secondary);
  transition: transform 0.2s ease;
}

:deep(.search-select.vs--open .vs__open-indicator) {
  transform: rotate(180deg);
}

:deep(.search-select.vs--open .vs__dropdown-toggle) {
  border-color: var(--primary-color);
  background-color: #ffffff;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
}







.content-textarea {
  width: 100%;
  padding: 16px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
  min-height: 400px;
  transition: border-color 0.3s ease;
  line-height: 1.6;
}

.content-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
}

.rewrite-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 8px;
}

.rewrite-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.rewrite-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.rewrite-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.rewrite-textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
  min-height: 300px;
  transition: border-color 0.3s ease;
  background: #f8f9fa;
}

.rewrite-textarea:focus {
  outline: none;
  border-color: #667eea;
  background: white;
}



.time-input-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.time-input {
  flex: 1;
  padding: 12px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.time-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.time-btn {
  padding: 12px 16px;
  background: var(--secondary-color);
  color: var(--text-color);
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.time-btn:hover {
  background: var(--secondary-hover);
  transform: translateY(-1px);
}

.upload-btn {
  width: 100%;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 18px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.upload-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-3px);
  box-shadow: 0 12px 30px rgba(102, 126, 234, 0.4);
}

.upload-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.upload-hint {
  margin-top: 8px;
  text-align: center;
  color: var(--text-secondary);
  font-size: 12px;
}

/* 图片上传样式 */
.image-upload-section {
  margin-bottom: 16px;
}

.image-upload-container {
  position: relative;
}

.image-upload-placeholder {
  width: 100%;
  height: 120px;
  border: 2px dashed var(--border-color);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafbfc;
}

.image-upload-placeholder:hover {
  border-color: var(--primary-color);
  background: rgba(59, 130, 246, 0.05);
}

.image-upload-placeholder.uploading {
  cursor: not-allowed;
  opacity: 0.7;
}

.upload-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.loading-spinner-small {
  width: 20px;
  height: 20px;
  border: 2px solid #e9ecef;
  border-top: 2px solid var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: var(--text-secondary);
}

.upload-text {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 4px;
}

.image-upload-hint {
  font-size: 12px;
  color: var(--text-secondary);
}

.image-preview-container {
  position: relative;
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-preview {
  width: 100%;
  height: 120px;
  object-fit: cover;
  display: block;
}

.image-actions {
  position: fixed;
  top: 8px;
  right: 8px;
  display: flex;
  gap: 4px;
}

.remove-image-btn,
.change-image-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.3s ease;
}

.remove-image-btn:hover,
.change-image-btn:hover {
  background: rgba(0, 0, 0, 0.9);
  transform: scale(1.1);
}

.remove-image-btn {
  background: rgba(239, 68, 68, 0.8);
}

.remove-image-btn:hover {
  background: rgba(239, 68, 68, 1);
}

.image-name {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}



/* 右侧面板样式 */
.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: hidden;
}

.filter-section {
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color);
  background: #fafbfc;
}

.filter-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: var(--text-color);
  font-weight: 600;
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-input {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.filter-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.filter-btn {
  padding: 8px 12px;
  background: var(--primary-color);
  color: var(--text-color);
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.filter-btn:hover {
  background: var(--primary-hover);
}

.filter-label {
  font-size: 14px;
  color: var(--text-color);
} 

.filter-select {
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 14px;
  background: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
  min-width: 100px;
}

.filter-select:focus {
  outline: none;
  border-color: var(--primary-color);
}

/* 楼盘选择器样式 */
.estate-select {
  min-width: 200px;
}

/* vue-select 在筛选区域的样式覆盖 */
:deep(.estate-select .vs__dropdown-toggle) {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: white;
  transition: border-color 0.3s ease;
  min-height: 36px;
}

:deep(.estate-select .vs__dropdown-toggle:focus) {
  border-color: var(--primary-color);
  outline: none;
}

:deep(.estate-select .vs__search) {
  padding: 0;
  margin: 0;
  border: none;
  background: transparent;
  font-size: 14px;
  color: var(--text-color);
  min-height: 20px;
}

:deep(.estate-select .vs__search::placeholder) {
  color: #94a3b8;
}

:deep(.estate-select .vs__dropdown-menu) {
  border: 1px solid var(--border-color);
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: white;
}

:deep(.estate-select .vs__dropdown-option) {
  padding: 8px 12px;
  font-size: 14px;
  color: var(--text-color);
  transition: background-color 0.2s ease;
}

:deep(.estate-select .vs__dropdown-option--highlight) {
  background: var(--primary-color);
  color: white;
}

:deep(.estate-select .vs__dropdown-option--selected) {
  background: rgba(59, 130, 246, 0.1);
  color: var(--primary-color);
}

:deep(.estate-select .vs__clear) {
  display: none;
}

:deep(.estate-select .vs__open-indicator) {
  fill: var(--text-secondary);
  transition: transform 0.2s ease;
}

:deep(.estate-select.vs--open .vs__open-indicator) {
  transform: rotate(180deg);
}

:deep(.estate-select.vs--open .vs__dropdown-toggle) {
  border-color: var(--primary-color);
  background-color: #ffffff;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
}



/* 表格区域样式 */
.table-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.table-section h3 {
  margin: 0;
  padding: 20px 24px 16px;
  font-size: 16px;
  color: var(--text-color);
  font-weight: 600;
  border-bottom: 1px solid var(--border-color);
}

.table-container {
  flex: 1;
  overflow: auto;
  padding: 0 24px;
  height: 100%;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  position: relative;
}

.data-table th {
  background: #f8f9fa;
  padding: 12px 8px;
  text-align: center;
  font-weight: 600;
  color: var(--text-color);
  border-bottom: 2px solid var(--border-color);
  position: sticky;
  top: 0;
  z-index: 10;
}

.data-table td {
  padding: 16px 8px;
  border-bottom: 1px solid #e9ecef;
  vertical-align: middle;
  text-align: center;
}

.data-table tr:hover {
  background: #f8f9fa;
}

.content-cell {
  max-width: 200px;
  color: #6c757d;
}

.content-text {
  max-height: 120px;
  overflow: hidden;
  line-height: 1.4;
  cursor: pointer;
  white-space: pre-line;
}

.extract-cell {
  max-width: 300px;
  color: #6c757d;
}

.extract-content {
  max-height: 120px;
  overflow: hidden;
  line-height: 1.4;
  cursor: pointer;
  white-space: pre-line;
}

.content-link {
  color: var(--text-secondary);
  text-decoration: none;
  font-weight: 600;
}

.content-link:hover {
  text-decoration: underline;
}

.source-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  color: white;
}

.source-xiaohongshu { background: #ff2442; }
.source-wechat { background: #27ae60; }
.source-website { background: #3498db; }
.source-douyin { background: #615b5c; }
.source-user { background: #9b59b6; }
.source-default { background: #6c757d; }

.time-cell {
  color: #6c757d;
  font-size: 13px;
  white-space: nowrap;
  min-width: 120px;
}

.property-cell {
  font-weight: 600;
  color: var(--text-secondary);
  max-width: 150px;
}

.comment-type-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.comment-type-tag.positive {
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
}

.comment-type-tag.negative {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.comment-type-tag.neutral {
  background: rgba(107, 114, 128, 0.1);
  color: #6b7280;
}

.comment-type-tag.constructive {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
}

.comment-type-tag.professional {
  background: rgba(168, 85, 247, 0.1);
  color: #a855f7;
}

/* 机器审核状态样式 */
.review-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.review-pass {
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
}

.review-reject {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.review-pending {
  background: rgba(245, 158, 11, 0.1);
  color: #f59e0b;
}

.review-default {
  background: rgba(107, 114, 128, 0.1);
  color: #6b7280;
}

/* 是否采用状态样式 */
.adopt-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.adopt-yes {
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
}

.adopt-no {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.adopt-default {
  background: rgba(107, 114, 128, 0.1);
  color: #6b7280;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  border-top: 1px solid var(--border-color);
  background: #fafbfc;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: white;
  color: var(--text-color);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background: var(--primary-hover);
  color: var(--text-color);
  border-color: var(--primary-hover);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: var(--text-color);
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 3000;
}

.loading-spinner {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  font-size: 16px;
  color: var(--primary-color);
}

/* 弹窗样式 */
.tooltip {
  position: fixed;
  z-index: 10000;
  background: rgba(0, 0, 0, 0.9);
  color: white;
  padding: 12px;
  border-radius: 8px;
  max-width: 400px;
  max-height: 300px;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-line;
  transform: translateX(-50%);
}

.tooltip-content {
  word-break: break-word;
}

/* 上传弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 500px;
  max-height: 80%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid var(--border-color);
  background: #fafbfc;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--text-color);
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: color 0.3s ease;
}

.modal-close:hover {
  color: var(--primary-color);
}

.modal-body {
  padding: 24px;
  flex-grow: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.modal-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.modal-item label {
  font-weight: 500;
  color: var(--text-color);
  font-size: 14px;
}

.modal-value {
  font-weight: 600;
  color: var(--text-secondary);
  font-size: 14px;
}

.modal-comment-content {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  color: var(--text-color);
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.modal-image-preview {
  max-width: 200px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.modal-image {
  width: 100%;
  height: auto;
  display: block;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid var(--border-color);
  background: #fafbfc;
}

.modal-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.modal-btn.cancel-btn {
  background: #e0e0e0;
  color: var(--text-color);
}

.modal-btn.cancel-btn:hover {
  background: #d0d0d0;
}

.modal-btn.confirm-btn {
  background: var(--primary-color);
  color: var(--text-color);
}

.modal-btn.confirm-btn:hover {
  background: var(--primary-hover);
}

.modal-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 采用弹窗样式 */
.adopt-modal {
  width: 90%;
  max-width: 800px;
  max-height: 90%;
}

.adopt-section {
  margin-bottom: 24px;
}

.adopt-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--text-color);
  font-weight: 600;
}

.adopt-estate-info {
  padding: 12px;
  background: #f8f9fa;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  display: flex;
  align-items: center;
}

.adopt-estate-name {
  font-size: 14px;
  color: var(--text-color);
  font-weight: 600;
  padding: 4px 8px;
  background: var(--primary-color);
  color: white;
  border-radius: 4px;
  display: inline-block;
}

.adopt-estate-search {
  width: 100%;
}

.adopt-search-select {
  width: 100%;
}



.adopt-content-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
  min-height: 120px;
  transition: border-color 0.3s ease;
}

.adopt-content-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
}

.adopt-rewrite-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 8px;
}

.adopt-rewrite-btn {
  padding: 6px 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.adopt-rewrite-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.adopt-rewrite-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.adopt-rewrite-textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
  min-height: 100px;
  transition: border-color 0.3s ease;
  background: #f8f9fa;
}

.adopt-rewrite-textarea:focus {
  outline: none;
  border-color: #667eea;
  background: white;
}

.adopt-time-input-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.adopt-time-input {
  flex: 1;
  padding: 10px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.adopt-time-input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.adopt-time-btn {
  padding: 10px 12px;
  background: var(--secondary-color);
  color: var(--text-color);
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.adopt-time-btn:hover {
  background: var(--secondary-hover);
  transform: translateY(-1px);
}

.status-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.status-btn {
  padding: 8px 16px;
  border: 2px solid #e9ecef;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 70px;
  background: white;
  color: #6c757d;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.status-btn::before {
  content: '';
  position: fixed;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.5s;
}

.status-btn:hover::before {
  left: 100%;
}

.status-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.status-btn.correct-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #d4edda, #c3e6cb);
  color: #155724;
  border-color: #c3e6cb;
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);
}

.status-btn.correct-btn.active {
  background: linear-gradient(135deg, #28a745, #20c997);
  color: white;
  border-color: #28a745;
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.4);
}

.status-btn.error-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #f8d7da, #f5c6cb);
  color: #721c24;
  border-color: #f5c6cb;
  box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}

.status-btn.error-btn.active {
  background: linear-gradient(135deg, #dc3545, #c82333);
  color: white;
  border-color: #dc3545;
  box-shadow: 0 2px 8px rgba(220, 53, 69, 0.4);
}

.status-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.status-btn:disabled::before {
  display: none;
}

/* 添加状态指示器 */
.status-btn::after {
  content: '';
  position: fixed;
  top: 50%;
  right: 8px;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: currentColor;
  opacity: 0;
  transform: translateY(-50%);
  transition: all 0.3s ease;
}

.status-btn.active::after {
  opacity: 1;
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.3);
}

/* 按钮文字样式 */
.btn-text {
  position: relative;
  z-index: 1;
  display: inline-block;
  transition: transform 0.2s ease;
}

.status-btn:hover .btn-text {
  transform: scale(1.05);
}

/* 状态单元格样式优化 */
.status-cell {
  min-width: 160px;
  padding: 12px 8px !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .status-buttons {
    flex-direction: column;
    gap: 6px;
  }
  
  .status-btn {
    min-width: 60px;
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .status-cell {
    min-width: 120px;
  }
}
</style> 